package com.dituhui.tool.gis;

import java.io.IOException;

import org.apache.log4j.Logger;

import com.dituhui.tool.io.Constants;
import com.dituhui.tool.io.HttpTool;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 路网测距
 * 
 * @author liweigu
 * 
 */
public class PathDistance {
	private static Logger LOGGER = Logger.getLogger(PathDistance.class);
	private static final String AMAP_DISTANCE_URL = Constants.getValue("amapDistanceUrl", "config.properties");
	private static final String KEY = "10d58a522366d2c2e8de07852e7ad59d";

	// http://lbs.amap.com/api/webservice/guide/api/direction#distance
	/**
	 * 测距
	 * 
	 * @return 测距结果
	 */
	public DistanceResult getDistance(Point startPoint, Point endPoint) {
		DistanceResult distanceResult = null;

		String param = "origins=" + startPoint.getX() + "," + startPoint.getY() + "&destination=" + endPoint.getX() + "," + endPoint.getY()
				+ "&output=json&key=" + KEY;
		String content = null;
		try {
			content = HttpTool.getContentByGET(PathDistance.AMAP_DISTANCE_URL, param);
		} catch (IOException e) {
			LOGGER.info("getDistance发送异常。param=" + param, e);
		}
		if (content != null) {
			JSONObject jsonObject = JSONObject.fromObject(content);
			int status = jsonObject.getInt("status");
			if (status == 1) {
				JSONArray jsonArray = jsonObject.getJSONArray("results");
				if (jsonArray.size() > 0) {
					JSONObject jsonObjectInArray = jsonArray.getJSONObject(0);
					double distance = jsonObjectInArray.getDouble("distance");
					double duration = jsonObjectInArray.getDouble("duration");
					distanceResult = new DistanceResult();
					distanceResult.setDistance(distance);
					distanceResult.setDuration(duration);
				}
			}
		}

		return distanceResult;
	}

	/**
	 * 测距结果
	 * 
	 * @author liweigu
	 * 
	 */
	public static class DistanceResult {
		private double distance;
		private double duration;

		/**
		 * 获取距离，单位公里。
		 * 
		 * @return 距离
		 */
		public double getDistance() {
			return distance;
		}

		/**
		 * 设置距离，单位公里。
		 * 
		 * @param distance 距离
		 */
		public void setDistance(double distance) {
			this.distance = distance;
		}

		/**
		 * 获取耗时，单位小时。
		 * 
		 * @return 耗时
		 */
		public double getDuration() {
			return duration;
		}

		/**
		 * 设置耗时，单位小时。
		 * 
		 * @param time 耗时
		 */
		public void setDuration(double duration) {
			this.duration = duration;
		}
	}
}
